package com.xtoad.ecms.common.web.base;

import com.xtoad.ecms.common.web.exception.ResultCodeEnum;

import java.io.Serializable;
import java.util.List;

/**
 * 统一返回结果封装类
 *
 * @param <T> data类型
 * @author xtoad
 * @date 2020/05/29
 */
public class Result<T extends Object> implements Serializable {

    private static final long serialVersionUID = 5073999110547349969L;
    private String code;
    private String msg;
    private T data;

    public String getCode() {
        return code;
    }

    public void setCode(final String code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(final String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    /**
     * 默认构造方法
     */
    public Result() {
    }

    /**
     * 构造方法
     *
     * @param code 返回码
     * @param msg  返回消息
     * @param data 返回数据
     */
    public Result(final String code, final String msg, final T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    /**
     * 构造请求成功时的返回对象
     *
     * @return 返回对象
     */
    public static Result success() {

        return new Result(ResultCodeEnum.SUCCESS.getCode(), ResultCodeEnum.SUCCESS.getMsg(), null);
    }

    /**
     * 构造请求成功时的返回对象
     *
     * @param data 数据信息
     * @return 返回对象
     */
    public static <T> Result<T> success(final T data) {

        return new Result(ResultCodeEnum.SUCCESS.getCode(), ResultCodeEnum.SUCCESS.getMsg(), data);
    }

    /**
     * 构造请求成功时的返回数组对象
     *
     * @param data 数据信息
     * @return 返回对象
     */
    public static <T> Result<List<T>> success(final List<T> data) {

        return new Result(ResultCodeEnum.SUCCESS.getCode(), ResultCodeEnum.SUCCESS.getMsg(), data);
    }

    /**
     * 构造请求失败时的返回对象
     *
     * @param code 错误码
     * @param msg  错误内容
     * @return 返回对象
     */
    public static Result failed(final String code, final String msg) {
        Result result = new Result();
        result.setCode(code);
        result.setMsg(msg);
        return result;
    }

    /**
     * 构造请求失败时的返回对象
     *
     * @param resultCode 错误码对象
     * @return 返回对象
     */
    public static Result failed(ResultCodeEnum resultCode) {
        Result result = new Result();
        result.setCode(resultCode.getCode());
        result.setMsg(resultCode.getMsg());
        return result;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("Result{");
        sb.append("code='").append(code).append('\'');
        sb.append(", msg='").append(msg).append('\'');
        sb.append(", data=").append(data);
        sb.append('}');
        return sb.toString();
    }
}
